<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input v-model="query.keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getCustomers">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="50">
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="120" sortable>
      </el-table-column>
      <el-table-column prop="path" label="路径" width="80" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="80" sortable>
        <template scope="scope">
          <span v-if="scope.row.state=='-1'" style="color: red">停用</span>
          <span v-if="scope.row.state=='1'" style="color: green">正常</span>
        </template>
      </el-table-column>
      <el-table-column prop="intro" label="简介" width="120" sortable>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="200" sortable>
      </el-table-column>
      <el-table-column prop="update_time" label="更新时间" width="200" sortable>
      </el-table-column>
      <el-table-column prop="manager.username" label="部门经理" width="100" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" width="100" sortable>
      </el-table-column>
      <!--<el-table-column prop="sex" label="性别" width="100" :formatter="formatSex" sortable>
      </el-table-column>-->
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="query.pageSize" :total="pageInfo.total" style="float:right;">
      </el-pagination>
    </el-col>

    <!--新增或编辑界面
    v-model="saveFormVisible" 老版本用
    :visible.sync 新版本用
    -->
    <el-dialog title="新增或编辑" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="customer" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="名字" prop="name">
          <el-input v-model="customer.name" auto-complete="off"></el-input>
        </el-form-item>
        <!--<el-form-item label="性别">
          <el-radio-group v-model="customer.sex">
            <el-radio class="radio" :label="1">男</el-radio>
            <el-radio class="radio" :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>-->
        <el-form-item label="部门经理" prop="manager">
          <el-select v-model="customer.manager" placeholder="请选择" value-key="id">
            <!--key唯一标识
                label选择之后显示到选择框中的值
                value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
                 必须要写  value-key="id"-->
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader v-model="customer.parent"
                       :options="deptTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item label="简介">
          <el-input type="textarea" v-model="customer.intro"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>

export default {
  data() {
    return {
      query:{
        currentPage: 1,//当前页码
        pageSize:10,//每页显示多少条
        keyword:''//关键字
      },
      pageInfo:{
        total:0,//总数 默认是0
        rows:[],//页面数据
        totalPage:0//页面数据条数
      },
      listLoading: false,
      sels: [],//列表选中列

      //新增和编辑的数据
      customer:{//创建时间和更新时间后端自动生成
        id:null,
        name:'',
        intro:'',
        manager: {},
        parent:{}
      },
      employees:[],/*保存员工数据*/
      deptTree:[],/*上级部门树*/
      saveFormVisible: false,//新增或编译界面是否显示
      saveLoading: false,
      saveFormRules: {
        name: [
          { required: true, message: '请输入部门名字', trigger: 'blur' }
        ]
      },

    }
  },
  methods: {
    //获取部门树
    getDeptTree(){
      this.$http.get("/customer/tree")
          .then(result=>{
            result = result.data
            if(result.success){
              this.deptTree = result.data;
            }else {
              this.$message({
                message: '获取分页数据失败！'+result.message,
                type: 'error'
              });
            }
          })
          .catch(result=>{
            console.log("出错了"+result.message)
          })
    },
    //获取员工
    getEmployees() {
      this.$http.get("/employee")
          .then(result=>{
            result = result.data
            if(result.success){
              this.employees = result.data;
            }else {
              this.$message({
                message: '获取数据失败！'+result.message,
                type: 'error'
              });
            }
          })
          .catch(result=>{
            console.log("出错了"+result.message)
          })
    },
    //性别显示转换
    /*formatSex: function (row, column) {
      return row.sex == 1 ? '男' : row.se.x == 0 ? '女' : '未知';
    },*/
    handleCurrentChange(val) {
      this.query.currentPage = val;
      this.getCustomers();
    },
    //获取部门列表
    getCustomers() {
      this.listLoading = true;
      this.$http.post("/customer",this.query)
          .then(result=>{
            result = result.data
            if(result.success){
              this.pageInfo.total = result.total;
              // this.customers = result.data.customers;
              this.pageInfo=result.data
            }else {
              this.$message({
                message: '获取分页数据失败！'+result.message,
                type: 'error'
              });
            }
            this.listLoading = false;
          })
          .catch(result=>{
            console.log("出错了"+result.message)
          })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        let id = row.id;
        this.$http.delete("/customer/"+id)
            .then(result => {
              //NProgress.done();
              result = result.data
              if(result.success){
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
              }else{
                this.$message({
                  message: '删除失败',
                  type: 'error'
                });
              }
              this.getCustomers();
              this.listLoading=false
            })
            .catch(result=>{
              this.$message({
                message: '异常',
                type: 'error'+result.message
              });
            })
      }).catch(() => {
        this.$message({
          message: '取消成功',
          type: 'error'
        });
      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      //回显
      this.customer = Object.assign({}, row);
      this.getEmployees();//获取员工数据
      this.getDeptTree();//获取部门树
      let path = this.customer.path; //完整的path 包含自己的
      if (path){
        console.log(path);
        let paths = path.split("/"); //根据/分割
        let idsStr = paths.slice(1,paths.length-1);//最后一个是自己 不要
        let idsInt = [];
        for (let i = 0; i <idsStr.length ; i++) {//封装成数组
          idsInt.push(parseInt(idsStr[i]));
        }
        console.log(idsInt);
        //做部门的回显
        this.customer.parent = idsInt;//这里部门就变成了一个数组
      }
      this.saveFormVisible = true;
    },
    //显示新增界面
    handleAdd: function () {
      //清空
      this.customer={
        id:null,
        name:'',
        intro:'',
        manager: {},
        parent:{}
      }

      this.getEmployees();//获取员工数据
      this.getDeptTree();//获取部门树
      this.saveFormVisible = true;
    },
    //保存
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.customer);
            //把数据转换成我们想要格式 parent: [1, 2]---》parent:{id:2} 只需要一个上级部门id 不需要爷爷级的
            if (para.parent){
              let parentIds = para.parent; // [1, 2]
              let parentId = parentIds[parentIds.length-1]; // 2
              para.parent = {"id":parentId} //parent:{id:2}
            }

            // para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
            this.$http.put("/customer",para)
                .then(result => {
                  result = result.data
                  if(result.success){

                    //NProgress.done();
                    this.$message({
                      message: '保存成功',
                      type: 'success'
                    })
                    this.$refs['saveForm'].resetFields();//重置表单
                    this.getCustomers();//保存完重新获取部门数据
                    this.saveFormVisible = false;//关闭对话框
                  }else{
                    this.$message({
                      message: '保存失败',
                      type: 'error'
                    })
                  }
                })
                .catch(result=>{
                  this.$message({
                    message: '保存失败',
                    type: 'error'+result.message
                  })
                });
            this.saveLoading = false;//关闭加载条
          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      let ids=[]//存放选中的id 传入后端的是一个数组
      for(var i=0;i<this.sels.length;i++){
        ids.push(this.sels[i].id)
      }
      // console.log(ids)

      // var ids = this.sels.map(item => item.id).toString();
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        // let para = {ids: ids};
        this.$http.patch("/customer",ids)
            .then(result => {
              result = result.data
              this.listLoading = false;
              //NProgress.done();
              if(result.success){
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
              }else {
                this.$message({
                  message: '删除失败',
                  type: 'error'+result.message
                });
              }
              this.getCustomers();
            });
      }).catch(() => {
      });
    }
  },
  mounted() {
    this.getCustomers();
  }
}

</script>

<style scoped>

</style>